/**
 * Created by WYH on 16/12/29.
 */

$(document).ready(function () {
    JudgeBrowser.changeTopBarTextSizeInIE();
    if(JudgeLogin.isLogin()) {
        SetupCity.setAddress(".provinceInput", ".cityInput", ".districtInput");
        bindClickEvent();

        InputCheck.checkInputValueIsNumber(".contactPhoneInput");
        JudgeLogin.bindSignOut(".signOut");
        setupCommunity();
    }
});


function bindClickEvent() {

    clickPerfectInformationButton();
    clickResetPassword();
    clickChangePhone();
    clickBuluoTitle();
    clickFileUploadInput();
}


/* 获取所有社区，并设置到界面上供选择 */
function setupCommunity() {
    Api.fetchCommunityList(function (result) {
        window.localStorage.communityList = JSON.stringify(result.data);
        SetCommunity.setupCommunity("#community_address", result);
        fetchCompanyInfo();
    }, function (error) {
        alert("获取社区列表失败!!!");
    })
}


/* 点击上传营业执照 */
function clickFileUploadInput() {
    $(".fileUploadInput").change(function () {
        var file = this.files[0];
        var fileReader = new FileReader();
        fileReader.onload = function (e) {
            var imgSrc = fileReader.result;
            setupLicenseImage(imgSrc);
        };
        fileReader.readAsDataURL(file);
    })
}

/* 改变营业执照图片的大小 */
function setupLicenseImage(imgSrc) {
    $(".licenseImageInput img").attr("src", imgSrc);
    $(".licenseImageInput img").addClass("complete_img");
}

/* 点击部落标题跳入staffList界面 */
function clickBuluoTitle() {
    $(".buluo").click(function () {
        window.location.href = "../../html/home/staffList.html";
    });

}

/* 检查必要的输入信息是否为空 */
function checkAllInputValid() {
    var promptAndModuleArr= [
        { prompt: "用户名不能为空", module: ".nameInput" },
        { prompt: '公司名称不能为空', module: ".companyNameInput" },
        { prompt: "公司地址不能为空", module: ".addressInput" },
        { prompt: "公司行业不能为空", module: ".companyIndustryInput" },
        { prompt: "联系人姓名不能为空", module: ".linkmanInput" },
        { prompt: "省份不能为空", module: ".provinceInput" },
        { prompt: "城市不能为空", module: ".cityInput" },
        { prompt: "地区不能为空", module: ".districtInput" }
    ];
    for (var i = 0 ; i < promptAndModuleArr.length; i++) {
        var promptAndModule = promptAndModuleArr[i];
        if (!checkInputValid(promptAndModule.prompt, promptAndModule.module)) {
            return false;
        }
    }
    return true;
}

/*
* 检查input框是否为空
* prompt 为空时的提示信息
* module 需要验证的input框
* */
function checkInputValid(prompt, module) {
    if ($(module).val() == "") {
        alert(prompt);
        return false;
    }
    return true;
}


/* 上传营业执照照片接口 */
function callUploadPictureService(data, file, detail) {

    Api.uploadPicture(data, function (result) {
        var imageUrl = "http://buluo-gs-pictures.oss-cn-beijing.aliyuncs.com/" + result.data.objectKey;
        var xhr = new XMLHttpRequest();
        xhr.open("PUT", result.data.url, true);
        xhr.setRequestHeader("Content-Type", "image/jpeg");
        xhr.onload = function () {
            if (xhr.status == 200) {
                detail.licensePicture = imageUrl;
                callPerfectCompanyInfoServer(detail);
            } else {
                alert("上传图片失败");
            }
        };
        xhr.send(file);



    }, function (error) {

    });
}

/* 点击完善按钮 */
function clickPerfectInformationButton() {
    $(".confirmChangeButton").click(function () {
        var detail = getChangeData();
        var fileObj = document.getElementById("uploadImage").files[0];

        if (fileObj != null) {
            var md5 = hex_md5(fileObj);
            callUploadPictureService(md5, fileObj, detail);

        } else {
            detail.licensePicture = window.localStorage.licensePicture;
            callPerfectCompanyInfoServer(detail);
        }

    });
}


/* 调用晚上公司信息接口 */
function callPerfectCompanyInfoServer(detail) {
    if (checkAllInputValid()) {
        Api.perfectCompanyInfo(detail, function (result) {
            console.log(result);

            if (result.code == 200) {
                alert("完善成功");
                window.scrollTo(0, 0);
                window.location.reload();
            }
        }, function (error) {
            alert("完善失败");
        })
    }
}




/* 点击充值密码 */
function clickResetPassword() {
    $(".resetPassword").click(function() {
        console.log("点击重置密码");
        window.location.href = "../../html/company/resetPassword.html";
    });
}

/* 点击修改手机号 */
function clickChangePhone() {
    $(".changePhone").click(function () {
        window.location.href = "../../html/company/changePhone.html";
    })
}


/* 获取输入的所有信息 */
function getChangeData() {
    var keyArr;
    if (window.localStorage.authenticationStatus == AuthenticationStatus.process) {
        keyArr = [ "name", "password", "companyName", "desc", "province", "companyStaffNum", "city", "district", "address", "companyIndustry", "companyNature", "linkman", "department", "phone", "mobilePhone", "email"];
    } else {
        keyArr = [ "name", "password", "companyName", "desc", "province", "companyStaffNum", "city", "district", "address", "companyIndustry", "companyNature", "linkman", "department", "phone", "mobilePhone", "email", "licenseNum", "licensePicture", "legalPersonName", "legalPersonIdCardNo", "legalPersonPhone"];
    }
    var changeData = {};
    keyArr.forEach(function (data, index) {
        changeData[data] = $("." + data + "Input").val();
    });
    changeData = getCommunityId(changeData);
    return changeData;
}


function getCommunityId(changeData) {
    var communityList = JSON.parse(window.localStorage.communityList);
    var selectIndex = document.getElementById("community_address").selectedIndex;
    var communityId = communityList[selectIndex].id;
    changeData['communityName'] = $("#community_address").val();
    changeData['communityId'] = communityId;
    return changeData;
}


var AuthenticationStatus =  function() {
    return {
        notStart: "NOT_START",
        processing: "PROCESSING",
        failure: "FAILURE",
        success: "SUCCESS"
    };
}();

function fetchCompanyInfo() {
    Api.fetchCompanyDetailInfo(function (result) {
        console.log(result);
        $(".managerBaseInfo").text("管理员：" + result.data.companyName);
        var infoData = result.data;

        Object.keys(infoData).forEach(function (data) {
            $("." + data + "Input").val(infoData[data]);
        });
        setupAuthenticationStatus(result.data.authenticationStatus);
        setupLicensePicture(result);
        setupCity(infoData);
        $("#community_address").val(infoData['communityName']);

    }, function (error) {

    });
}

function setupAuthenticationStatus(status) {
    window.localStorage.authenticationStatus = status;
    if (status == AuthenticationStatus.processing) {
        $(".legalPersonNameInput").attr("disabled", "disabled");
        $(".legalPersonIdCardNoInput").attr("disabled", "disabled");
        $(".legalPersonPhoneInput").attr("disabled", "disabled");
        $(".licenseNumInput").attr("disabled", "disabled");
        $(".fileUploadInput").attr("disabled", "disabled");
    }
}

function setupLicensePicture(result) {
    if (result.data.licensePicture != null) {
        window.localStorage.licensePicture = result.data.licensePicture;
        setupLicenseImage(result.data.licensePicture);
    }
}

function setupCity(infoData) {
    $(".provinceInput").val(infoData.province);
    $(".provinceInput").change();
    $(".cityInput").val(infoData.city);
    $(".cityInput").change();
    $(".districtInput").val(infoData.district);
    $(".districtInput").change();
}


